Friday, October 25, 2024

C# Situation in which you should use static method

Static methods in C# are often used in situations where you need to perform an operation that is not dependent on the state of an instance of a class. Here's an example situation where you should use a static method.

Suppose you have a class called MathUtilities that provides various mathematical operations. These operations do not rely on any specific instance of the class, but rather they operate on the input parameters directly.
public class MathUtilities
{
    // Static method to calculate the sum of two numbers
    public static int Add(int a, int b)
    {
        return a + b;
    }

    // Static method to calculate the product of two numbers
    public static int Multiply(int a, int b)
    {
        return a  b;
    }
}
In this example, Add and Multiply are static methods because they don't need to maintain any internal state, and they perform their operations solely based on the input parameters. You can use these methods without creating an instance of the MathUtilities class, like so:
int sum = MathUtilities.Add(5, 3);        // Call the static Add method
int product = MathUtilities.Multiply(4, 7); // Call the static Multiply method
Using static methods in this way allows you to encapsulate related functionality within a class without requiring object instantiation, which can make your code more organized and efficient when you have utility functions or operations that don't need to maintain state.

No comments:

Post a Comment

Hot Topics